package com.wondersgroup.wuhan_demo.ui;

import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.wondersgroup.wuhan_demo.MyApplication;
import com.wondersgroup.wuhan_demo.R;
import com.wondersgroup.wuhan_demo.base.BaseFragment;
import com.wondersgroup.wuhan_demo.util.DataUtil;
import com.wondersgroup.wuhan_demo.util.SPUtils;

import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.mrobot.core.log.LogUtils;
import cn.mrobot.pkgcore.cookyplus.printer.MThermalPrinter;
import cn.mrobot.pkgcore.cookyplus.printer.TPrinterState;
import cn.mrobot.pkgcore.cookyplus.printer.builder.Line;
import cn.mrobot.pkgcore.cookyplus.printer.builder.MThermalPrinterBuilder;
import cn.mrobot.pkgcore.cookyplus.printer.listener.PrinterListener;
import cn.mrobot.pkgcore.cookyplus.printer.printer.MGpThermalPrinter;
import cn.mrobot.pkgcore.core.ErrorCode;

public class PaySuccFragment extends BaseFragment implements PrinterListener {

    @BindView(R.id.tv_result)
    TextView tvResult;
    Unbinder unbinder;
    private String TAG = this.getClass().getSimpleName();
    private static final String XML_NAME = "print_template.xml";
    Context context;
    private MThermalPrinter mTPrinter;
    private int PRINTWHAT = 0x124;
    //    private IPrintReader mPrintReader = null;
    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == PRINTWHAT) {
                printTest();
            }
        }

    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_pay_succ, container, false);
        unbinder = ButterKnife.bind(this, view);
        tvResult.setText("预约成功！\n请您拿好挂号凭条！");
        context=getContext();
        initPrint();
//        printTest();
        handler.sendEmptyMessageDelayed(PRINTWHAT, 3000);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        LaunchActivity launchActivity = (LaunchActivity) getActivity();
        launchActivity.setTopPosition(0);
    }

    private void initPrint() {
        mTPrinter = MGpThermalPrinter.get();
        mTPrinter.init(MyApplication.getContextObject());
        mTPrinter.open();
        mTPrinter.registerListener(this);
//        try {
//            mPrintReader = new ThermalPrintReader(MyApplication.getContextObject(), XML_NAME);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mTPrinter.unregisterListener(this);
        mTPrinter.close();
    }

    public void printTest() {
        mTPrinter.printBuilder(getPrinterBuilder());
        //直接切纸
//        mTPrinter.cut();
    }

    private MThermalPrinterBuilder getPrinterBuilder() {
        Resources resources = context.getResources();
        String kh = (String) SPUtils.get(context, resources.getString(R.string.kh), "");
        String xm = (String) SPUtils.get(context, resources.getString(R.string.xm), "");
        String xb = (String) SPUtils.get(context, resources.getString(R.string.xb), "");
        return new MThermalPrinterBuilder()
                .newLine(new Line().center().doubleSize().notUnderline().content("万达信息股份有限公司")).newLine()
                .newLine(new Line().center().notUnderline().content("预约凭条")).newLine()
                .newLine(new Line().start().normalSize().notUnderline().content("    ").content("卡号：" + kh)).newLine()
                .newLine(new Line().content("    ").content("姓名：" + xm)).newLine()
                .newLine(new Line().content("    ").content("性别：" + xb)).newLine()
                .newLine(new Line().content("    ").content("科室：" + MyApplication.deptName)).newLine()
                .newLine(new Line().content("    ").content("医生：" + MyApplication.doctorName)).newLine()
                .newLine(new Line().content("    ").content("打印日期：" + DataUtil.ConverToString(new Date()))).newLine(1)
                .newLine().newLine(new Line().center().normalSize().underline().content("凭此小票可至万达信息展厅领取饮料一瓶"))
                .newLine(new Line().content("请妥善保管好您的挂号凭条")).newLine(3)
                .newLine(new Line().cutPaper());
    }

    @Override
    public void onStateChanged(final boolean connected, final TPrinterState stateCode) {
        LogUtils.d(TAG, "connected = " + connected + ", stateCode = " + stateCode);
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
//                Toast.makeText(MyApplication.getContextObject(),
//                        "connected = " + connected + ", stateCode = " + stateCode,
//                        Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onPrintError(final ErrorCode error) {
        Log.i(TAG, "ErrorCode = " + error.getCode() + ", message = " + error.getMessage());
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
//                Toast.makeText(MyApplication.getContextObject(),
//                        "ErrorCode = " + error.getCode() + ", message = " + error.getMessage(),
//                        Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick(R.id.tv_dh)
    public void onViewClicked() {
        addFragment(DhFragment.newInstance());
    }
}
